﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Batty
{
    class Rats
    {



        public class Rat
        {
            public Pondhawk game;
            public Model model;
            public int frontleft;          // Index to the wing 1 bone
            public int frontright;          // Index to the wing 2 bone
            public int backleft;          // Index to the wing 1 bone
            public int backright;          // Index to the wing 2 bone
            public float legangle1 = 0f; // Current wing deployment angle
            public float legangle2 = -.8f; // Current wing deployment angle
            public int legState = 1;
            public bool confused = false;
            public float speed = 2;
            public Vector3 position = Vector3.Zero;
            public float azimuth = 0;
            public bool remove=false;


            public void DrawModel(GraphicsDeviceManager graphics, Model model, Matrix world, Pondhawk game)
            {
                Matrix[] transforms = new Matrix[model.Bones.Count];
                model.CopyAbsoluteBoneTransformsTo(transforms);
                transforms[frontleft] = Matrix.CreateRotationX(legangle1) * transforms[frontleft];
                transforms[frontright] = Matrix.CreateRotationX(-legangle1) * transforms[frontright];
                transforms[backleft] = Matrix.CreateRotationX(-legangle1) * transforms[backleft];
                transforms[backright] = Matrix.CreateRotationX(legangle1) * transforms[backright];






                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (BasicEffect effect in mesh.Effects)
                    {
                        effect.EnableDefaultLighting();
                        effect.World = transforms[mesh.ParentBone.Index] * world;
                        effect.View = game.Camera.View;
                        effect.Projection = game.Camera.Projection;
                    }
                    mesh.Draw();
                }
            }
        }









        private Pondhawk game;
        public LinkedList<Rat> rats = new LinkedList<Rat>();
        public LinkedList<Rat> RatsList { get { return rats; } }
        public LinkedList<Rat> ratsCopy = new LinkedList<Rat>();
        public LinkedList<Rat> RatsListCopy { get { return ratsCopy; } }
        private Random random = new Random();




        public Rats(Pondhawk game)
        {
            this.game = game;
        }
        public void LoadContent(ContentManager content)
        {
 
            while (rats.Count < 20)
            {
                Rat rat = new Rat();
                rat.model = content.Load<Model>("Rat-rigid");
                rat.frontleft = rat.model.Bones.IndexOf(rat.model.Bones["LeftFrontLeg"]);
                rat.frontright = rat.model.Bones.IndexOf(rat.model.Bones["RightFrontLeg"]);
                rat.backleft = rat.model.Bones.IndexOf(rat.model.Bones["LeftBackLeg"]);
                rat.backright = rat.model.Bones.IndexOf(rat.model.Bones["RightBackLeg"]);
                rat.position = RandomXZVector(-20, 20);
                rats.AddLast(rat);
           }

        }
        
        public void Update(GameTime gameTime)
        {


            foreach (Rat rat in RatsList){





                float legMoveTime = .7f;
                if (rat.legState == 0)
                    rat.legangle1 += (float)(0.30 * gameTime.ElapsedGameTime.TotalSeconds / legMoveTime);
                else
                    rat.legangle1 -= (float)(0.30 * gameTime.ElapsedGameTime.TotalSeconds / legMoveTime);
                if (rat.legangle1 >= 0.30f)
                {
                    rat.legangle1 = 0.30f;
                    rat.legState = 1;
                }
                if (rat.legangle1 <= -0.30f)
                {
                    rat.legangle1 = -0.30f;
                    rat.legState = 0;
                }
                Matrix transform = Matrix.CreateRotationY(rat.azimuth);
                Vector3 directedThrust = Vector3.TransformNormal(new Vector3(0, 0, 1), transform);
                rat.position += directedThrust * rat.speed * (float)gameTime.ElapsedGameTime.TotalSeconds;
               // System.Diagnostics.Trace.WriteLine(rat.legangle1.ToString());
            }
          
            //RatsListCopy=RatsList.ToArray();
        }

        public void Draw(GraphicsDeviceManager graphics, GameTime gameTime,Pondhawk game)
        {
            foreach (Rat rat in RatsList)
            {

                Matrix transform = Matrix.CreateRotationY(rat.azimuth) * Matrix.CreateTranslation(rat.position);

                rat.DrawModel(graphics, rat.model, transform, game);
          
            }

        }


        public void addRat()
        {
            //after a given amount of time add a rat
        }

        private Vector3 RandomXZVector(float min, float max)
        {
            return new Vector3((float)(min + (random.NextDouble() * (max - min))),
                (float)5,
                (float)(min + (random.NextDouble() * (max - min))));
        }


        public bool testEchoForCollision(BoundingSphere sphere)
        {
            //change direction of rat
            return false;
        }
        public bool finishCollision()
        {
            for (LinkedListNode<Rat> ratNode = RatsList.First; ratNode != null; )
            {
                LinkedListNode<Rat> nextNode = ratNode.Next;
                Rat rattest = ratNode.Value;

                if (ratNode.Value.remove == true )
                {
                  //  System.Diagnostics.Trace.WriteLine(RatsList.Count().ToString());
                   // try
                    //{
                        rats.Remove(ratNode);

                       // System.Diagnostics.Trace.WriteLine("Removing Rats");
              /*      }
                    catch (Exception e)
                    {
                        System.Diagnostics.Trace.WriteLine(e.ToString());
                    }*/
                }
            }
            return false;
        }
        public bool testRatsForCollision(Rat rat)
        {
            //for rat in rats test with rats after it
            //remove both rats, make a squeal sound

            //my bounding spheres are wrong!!!!!!!!!!!!!!!
         
                BoundingSphere ratsphere = rat.model.Meshes[0].BoundingSphere;
                ratsphere = ratsphere.Transform(rat.model.Bones[0].Transform);
                ratsphere.Center += rat.position;
              //  System.Diagnostics.Trace.WriteLine("Checking Rats");
                for (LinkedListNode<Rat> ratNode = RatsList.First; ratNode != null; )
                {
                    LinkedListNode<Rat> nextNode = ratNode.Next;
                    Rat rattest = ratNode.Value;
                    //System.Diagnostics.Trace.WriteLine("Checking Rats2");
                    // Obtain a bounding sphere for the asteroid.  I can get away
                    // with this here because I know the model has exactly one mesh
                    // and exactly one bone.
                    BoundingSphere bs = rattest.model.Meshes[0].BoundingSphere;
                    bs = bs.Transform(rattest.model.Bones[0].Transform);

                    // Move this to world coordinates.  Note how easy it is to 
                    // transform a bounding sphere
                    bs.Radius += 4;
                    bs.Center += rattest.position;

                    if (ratsphere.Intersects(bs)&& ratsphere.Center!=bs.Center)
                    {
                        //System.Diagnostics.Trace.WriteLine("Removing Rats");
                        ratNode.Value.remove = true;
                       // rats.Remove(ratNode);
                    }
                    else{
                      //  rats.Remove(ratNode);
                       // System.Diagnostics.Trace.WriteLine("NOT Removing Rats");
                       // ratsCopy.AddLast(rat);
                   
                    }
                   
                    ratNode = nextNode;
                }

                if (rat.remove == false)
                    ratsCopy.AddLast(rat);
               // System.Diagnostics.Trace.WriteLine("Rats Copy COunt:" + ratsCopy.Count().ToString());


            /*
            for (LinkedListNode<Rat> ratNode2 = RatsList.First; ratNode2 != null; )
            {
                LinkedListNode<Rat> nextNode = ratNode2.Next;
                Rat rattest2 = ratNode2.Value;
                if (rattest2.remove == true)
                    RatsList.Remove(ratNode2);
            }
            */
            return false;
        }

        public void checkConfusionState()
        {
            //checktimesinceconfused
            //if no longer confused make them go to lego block again
        }

    }
}
